package com.haixiaoke.smartLock.yaluete;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.common.core.redis.RedisCache;
import com.haixiaoke.common.exception.ServiceException;
import com.haixiaoke.common.utils.sign.AesUtils;
import com.haixiaoke.domain.*;
import com.haixiaoke.service.*;
import com.haixiaoke.smartLock.base.SmartLockBasicsService;
import com.haixiaoke.vo.YltAuthVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 亚略特智能锁接口
 *
 * @author qixi
 * 2023-06-01
 */
@Service
@Slf4j
public class SmartLockYLTService implements SmartLockBasicsService {
    @Autowired
    private RedisCache redisCache;
    @Value("${yaluete.url}")
    private String yltApiUrl;
    @Value("${yaluete.appKey}")
    private String yltAppKey;
    @Value("${yaluete.secret}")
    private String yltSecret;
    @Value("${yaluete.merchantNumber}")
    private String yltMerchantNumber;

    @Autowired
    private ILockYltAccreditService lockYltAccreditService;
    @Autowired
    private ISmartLockBluetoothService smartLockBluetoothService;
    @Autowired
    private ISmartLockCardService smartLockCardService;
    @Autowired
    private ISmartLockFingerprintService smartLockFingerprintService;
    @Autowired
    private ISmartLockPwdService smartLockPwdService;


    /**
     * 获取ylt平台token
     *
     * @return
     */
    public String getToken() {
        String yltToken = redisCache.getCacheObject("yltToken");
        if (StringUtils.isEmpty(yltToken)) {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("fName", yltAppKey);
                // 亚略特秘钥需要加密
                String md5Pwd = SecureUtil.md5(yltSecret);
                map.put("fPassWord", md5Pwd);
                // 用户类型，默认2
                map.put("fUserType", "2");
                String jsonStr = JSONUtil.toJsonStr(map);
                String result = HttpUtil.post(yltApiUrl + "api/login", jsonStr);
                JSONObject resultJson = JSON.parseObject(result);
                String code = Convert.toStr(resultJson.get("code"));

                if ("0".equals(code)) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (data != null) {
                        String token = data.get("token").toString();
                        redisCache.setCacheObject("yltToken", token, 145, TimeUnit.MINUTES);
                        return token;
                    }
                } else {
                    String message = resultJson.get("message").toString();
                    return message;
                }
            } catch (Exception e) {
                return "获取失败";
            }
        }
        return yltToken;
    }

    @Override
    public String getSmartLock(SmartLock smartLock) {
        String yltToken = getToken();
        Map<String, Object> map = new HashMap<>();
        // 锁 MAC 编号
        map.put("fMAC", smartLock.getSn());
        map.put("pageSize", 10);
        map.put("pageNum", 0);
        // 商户编号
        map.put("fMerchantNumber", yltMerchantNumber);
        String jsonStr = JSONUtil.toJsonStr(map);
        String result = HttpRequest.post(yltApiUrl + "api/lockinfo/selectLockinfoList")
                .body(jsonStr)
                .header("Authorization", yltToken)
                .timeout(20000)// 超时，毫秒
                .execute()
                .body();
        return result;
    }

    @Override
    public String getSmartLockDetails(SmartLock smartLock) {
        return getAuthInfo(smartLock);
    }

    @Override
    public String getLockPassword(SmartLock smartLock) {
        return getAuthInfo(smartLock);
    }

    @Override
    public String getBluetooth(SmartLock smartLock) {
        return getAuthInfo(smartLock);
    }

    @Override
    @Transactional
    public String deleteBle(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_FALSE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_FALSE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    @Transactional
    public String addBluetooth(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除授权再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_TRUE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_TRUE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    @Transactional
    public String addFingerprint(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除授权再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByFinger(LockYltAccredit.AUTH_STATE_TRUE);
                    yltAuthVo.setFFingerFeature(smartLock.getFingerprint());
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByFinger(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFFingerFeature(smartLock.getFingerprint());
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    public String sendFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    @Transactional
    public String deleteFingerprint(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_FALSE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByBLE(LockYltAccredit.AUTH_STATE_FALSE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    public String offlinePassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String remoteUnlock(SmartLock smartLock) {
        return null;
    }

    @Override
    @Transactional
    public String addPassword(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_TRUE);
                    yltAuthVo.setFOpenPassword(smartLock.getPassword());
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFOpenPassword(smartLock.getPassword());
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    @Transactional
    public String deletePwd(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_FALSE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_FALSE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }

        return null;
    }

    @Override
    @Transactional
    public String addCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_TRUE);
                    yltAuthVo.setFICCardNumber(smartLock.getCardNumber());
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFICCardNumber(smartLock.getCardNumber());
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    @Transactional
    public String deleteCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_FALSE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_FALSE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }

        return null;
    }

    /**
     * 新增身份证开门
     *
     * @param smartLock
     * @return
     */
    @Transactional
    public String addIdCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_TRUE);
                    yltAuthVo.setFIDCardID(smartLock.getCardNumber());
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFIDCardID(smartLock.getCardNumber());
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    /**
     * 删除身份证授权
     *
     * @param smartLock
     * @return
     */
    @Transactional
    public String deleteIdCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        smartLock.setDelAuthState(1);
        // 先删除所有再新增
        if (StrUtil.isNotEmpty(yltAuthVo.getAuthorizationID())) {
            String resultStr = deleteAuth(smartLock);
            if (StrUtil.isNotEmpty(resultStr)) {
                String code = JSONObject.parseObject(resultStr).get("code").toString();
                if ("0".equals(code)) {
                    yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_FALSE);
                    smartLock.setYltAuthVo(yltAuthVo);
                    return addAuth(smartLock);
                }
            }
        } else {
            yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_FALSE);
            smartLock.setYltAuthVo(yltAuthVo);
            return addAuth(smartLock);
        }
        return null;
    }

    @Override
    public String getUnlockKey(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addFaceImage(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteFace(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getTaskList(SmartLock smartLock) {
        return null;
    }

    public String getAuthInfo(SmartLock smartLock) {
        String token = getToken();
        String sn = smartLock.getSn();

        Map<String, Object> map = new HashMap<>();
        map.put("fLockMAC", sn);
        map.put("fNumber", yltMerchantNumber);
        map.put("pageSize", 20);
        map.put("pageNum", 0);
        // 1,启用;2,禁用
        map.put("fStatus", 1);
        String jsonStr = JSONUtil.toJsonStr(map);
        String result = HttpRequest.post(yltApiUrl + "api/lock/select")
                .body(jsonStr)
                .header("Authorization", token)
                .timeout(20000)// 超时，毫秒
                .execute()
                .body();
        return result;
    }


    /**
     * 锁绑定商户
     */
    public String lockBindingMerchants(SmartLock smartLock) {
        String token = getToken();
        String sn = smartLock.getSn();

        Map<String, Object> map = new HashMap<>();
        map.put("fLockMAC", sn);
        map.put("fNumber", yltMerchantNumber);
        String jsonStr = JSONUtil.toJsonStr(map);
        String result = HttpRequest.post(yltApiUrl + "api/lockmerchant/merchantinfoBindLock")
                .body(jsonStr)
                .header("Authorization", token)
                .timeout(20000)// 超时，毫秒
                .execute()
                .body();
        return result;

    }

    /**
     * 解绑商户
     */
    public String untieMerchants(String sn) {
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("fLockMAC", sn);
        String jsonStr = JSONUtil.toJsonStr(map);
        String result = HttpRequest.post(yltApiUrl + "api/lockmerchant/merchantinfoUnBindLock")
                .body(jsonStr)
                .header("Authorization", token)
                .timeout(20000)// 超时，毫秒
                .execute()
                .body();
        return result;

    }

    public String addAuth(SmartLock smartLock) {
        String token = getToken();
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        String sn = smartLock.getSn();

        String appUserID = yltAuthVo.getFAppUserID();

        String aesUserId = null;
        try {
            aesUserId = AesUtils.aesEncrypt(appUserID, sn);
        } catch (Exception e) {
            throw new ServiceException("aes加密异常!");
        }

        Date fBeginDate = yltAuthVo.getFBeginDate();
        Date fEndDate = yltAuthVo.getFEndDate();

        Map<String, Object> map = new HashMap<>();
        map.put("fLockMAC", sn);
        map.put("fNumber", yltMerchantNumber);
        // 授权用户 ID（要求32位的16进制数）
        map.put("fAppUserID", aesUserId);
        map.put("fBeginDate", DateUtil.format(fBeginDate, "yyyy-MM-dd HH:mm:ss"));
        map.put("fEndDate", DateUtil.format(fEndDate, "yyyy-MM-dd HH:mm:ss"));

        // 密码
        Integer fOpenPassword = yltAuthVo.getFOpenByPassword();
        map.put("fOpenByPassword", fOpenPassword);
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(fOpenPassword)) {
            String pwd = yltAuthVo.getFOpenPassword();
            map.put("fOpenPassword", pwd);
        }

        // 身份证
        Integer fOpenByIDCard = yltAuthVo.getFOpenByIDCard();
        map.put("fOpenByIDCard", fOpenByIDCard);
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(fOpenByIDCard)) {
            String fidCardID = yltAuthVo.getFIDCardID();
            map.put("fIDCardID", fidCardID);
        }


        // 蓝牙
        Integer fOpenByBLE = yltAuthVo.getFOpenByBLE();
        map.put("fOpenByBLE", fOpenByBLE);

        // 指纹
        Integer fOpenByFinger = yltAuthVo.getFOpenByFinger();
        map.put("fOpenByFinger", fOpenByFinger);
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(fOpenByFinger)) {
            String fFingerFeature = yltAuthVo.getFFingerFeature();
            map.put("fFingerFeature", fFingerFeature);
        }


        // IC卡
        Integer fOpenByICCard = yltAuthVo.getFOpenByICCard();
        map.put("fOpenByICCard", fOpenByICCard);
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(fOpenByICCard)) {
            String icCard = yltAuthVo.getFICCardNumber();
            map.put("fICCardNumber", icCard);
        }
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        String jsonStr = JSONUtil.toJsonStr(list);
        String result = HttpRequest.post(yltApiUrl + "api/lock/authorization")
                .body(jsonStr)
                .header("Authorization", token)
                .timeout(20000)// 超时，毫秒
                .execute()
                .body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (!"0".equals(code)) {
            String msg = jsonObject.get("message").toString();
            log.error("亚略特新增授权异常 msg: -{}", msg);
            throw new ServiceException(" 亚略特新增授权异常! ");
        }
        // 入库授权信息
        addYltAuthInfo(yltAuthVo, result);
        return result;
    }


    public String untieLockAuth(String sn) {
        SmartLock smartLock = new SmartLock();
        smartLock.setSn(sn);
        smartLock.setDelAuthState(2);
        String result = deleteAuth(smartLock);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (!"0".equals(code)) {
            String msg = jsonObject.get("message").toString();
            log.error("亚略特解绑授权异常 msg: -{}", msg);
            throw new ServiceException(" 亚略特解绑授权异常! ");
        }
        return untieMerchants(sn);
    }

    public String deleteAuth(SmartLock smartLock) {
        log.info("三代锁删除授权");
        String sn = smartLock.getSn();
        String userFlag = smartLock.getIdentification();
        String token = getToken();
        if (StrUtil.isEmpty(sn)) {
            log.error("三代锁删除授权异常: 参数有误");
            throw new ServiceException("三代锁删除授权异常: 参数有误");
        }

        Integer delAuthState = smartLock.getDelAuthState();
        Map<String, Object> map = new HashMap<>();
        map.put("fLockMAC", sn);

        // 单个删除
        if (StrUtil.isNotEmpty(userFlag) && 1 == delAuthState) {
            LockYltAccredit accredit = lockYltAccreditService.selectLockYltAccreditByLockSNAndIdentification(sn, userFlag);
            if (ObjectUtil.isNull(accredit)) {
                log.error("三代锁删除授权异常: 用户授权未找到");
                throw new ServiceException("用户授权未找到");
            }
            String authId = accredit.getAuthId();
            map.put("fAuthorizationID", authId);
            map.put("fNumber", yltMerchantNumber);

            String jsonStr = JSONUtil.toJsonStr(map);
            String resultStr = HttpRequest.post(yltApiUrl + "api/lock/deauthorize")
                    .body(jsonStr)
                    .header("Authorization", token)
                    .timeout(20000)// 超时，毫秒
                    .execute()
                    .body();
            JSONObject result = JSONObject.parseObject(resultStr);
            String code = result.get("code").toString();
            if ("0".equals(code)) {
                // 删除成功将本地存储的授权信息清除

                // 蓝牙授权
                if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getBluetoothUnlockState()) {
                    smartLockBluetoothService.deleteSmartLockBluetoothByLockSNAndIdentification(sn, userFlag);
                }

                // 身份证授权
                if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getCardUnlockState()) {
                    smartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(sn, userFlag, SmartLockCard.IDENTITY_CARD_TYPE);
                }

                // ic卡授权
                if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getIcCardUnlockState()) {
                    smartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(sn, userFlag, SmartLockCard.CPU_CARD_TYPE);
                }

                // 指纹授权
                if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getFingerUnlockState()) {
                    smartLockFingerprintService.deleteSmartLockFingerprintByLockSNAndIdentification(sn, userFlag);
                }

                // 密码授权
                if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getPwdUnlockState()) {
                    smartLockPwdService.deleteSmartLockPwdBySnAndIdentification(sn, userFlag);
                }
                // ylt授权信息
                lockYltAccreditService.deleteLockYltAccreditById(accredit.getId());
            }
            return resultStr;
        } else {
            // 删除所有
            String jsonStr = JSONUtil.toJsonStr(map);
            String resultStr = HttpRequest.post(yltApiUrl + "api/lock/deauthorize")
                    .body(jsonStr)
                    .header("Authorization", token)
                    .timeout(20000)// 超时，毫秒
                    .execute()
                    .body();
            JSONObject result = JSONObject.parseObject(resultStr);
            String code = result.get("code").toString();
            if ("0".equals(code)) {
                // 蓝牙授权
                smartLockBluetoothService.deleteSmartLockBluetoothByLockSNAndIdentification(sn, null);

                // 身份证授权
                smartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(sn, null, SmartLockCard.IDENTITY_CARD_TYPE);

                // ic卡授权
                smartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(sn, null, SmartLockCard.CPU_CARD_TYPE);

                // 指纹授权
                smartLockFingerprintService.deleteSmartLockFingerprintByLockSNAndIdentification(sn, null);

                // 密码授权
                smartLockPwdService.deleteSmartLockPwdBySnAndIdentification(sn, null);
                // ylt授权信息
                lockYltAccreditService.deleteLockYltAccreditByLockSN(sn);
            }
            return resultStr;
        }
    }


    public void addYltAuthInfo(YltAuthVo vo, String result) {
        if (StrUtil.isNotEmpty(result)) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.get("code").toString();
            if ("0".equals(code)) {
                String identification = vo.getFAppUserID();
                // 亚略特用户授权信息
                LockYltAccredit yltAccredit = new LockYltAccredit();
                yltAccredit.setPwdUnlockState(vo.getFOpenByPassword().longValue());
                yltAccredit.setIcCardUnlockState(vo.getFOpenByICCard().longValue());
                yltAccredit.setFingerUnlockState(vo.getFOpenByFinger().longValue());
                yltAccredit.setCardUnlockState(vo.getFOpenByIDCard().longValue());
                yltAccredit.setBluetoothUnlockState(vo.getFOpenByBLE().longValue());
                yltAccredit.setAuthStartTime(vo.getFBeginDate());
                yltAccredit.setAuthEndTime(vo.getFEndDate());
                yltAccredit.setIdentification(identification);

                String data = jsonObject.getString("data");
                String lockOpenCommands = JSONObject.parseObject(data).getString("lockOpenCommands");
                // 授 权 ID
                JSONArray jsonArray = JSON.parseArray(lockOpenCommands);
                for (Object object : jsonArray) {

                    // sn
                    String fLockMAC = JSONObject.parseObject(object.toString()).getString("fLockMAC");
                    yltAccredit.setLockSn(fLockMAC);

                    // 授 权 ID
                    String authorizationID = JSONObject.parseObject(object.toString()).getString("fAuthorizationID");
                    yltAccredit.setAuthId(authorizationID);

                    // 身份证号
                    String fIDCardNumber = JSONObject.parseObject(object.toString()).getString("fIDCardNumber");
                    if (StrUtil.isNotEmpty(fIDCardNumber)) {
                        SmartLockCard idCard = new SmartLockCard();
                        idCard.setSn(fLockMAC);
                        idCard.setIdentification(identification);
                        idCard.setCardType(SmartLockCard.IDENTITY_CARD_TYPE);
                        idCard.setCardNumber(fIDCardNumber);
                        idCard.setStartTime(vo.getFBeginDate());
                        idCard.setEndTime(vo.getFEndDate());
                        smartLockCardService.insertSmartLockCard(idCard);
                    }

                    // ic卡
                    String fICCardNumber = JSONObject.parseObject(object.toString()).getString("fICCardNumber");
                    if (StrUtil.isNotEmpty(fICCardNumber)) {
                        SmartLockCard idCard = new SmartLockCard();
                        idCard.setSn(fLockMAC);
                        idCard.setIdentification(identification);
                        idCard.setCardType(SmartLockCard.CPU_CARD_TYPE);
                        idCard.setCardNumber(fICCardNumber);
                        idCard.setStartTime(vo.getFBeginDate());
                        idCard.setEndTime(vo.getFEndDate());
                        smartLockCardService.insertSmartLockCard(idCard);
                    }

                    // 密码
                    String fOpenPassword = JSONObject.parseObject(object.toString()).getString("fOpenPassword");
                    if (StrUtil.isNotEmpty(fOpenPassword)) {
                        SmartLockPwd pwd = new SmartLockPwd();
                        pwd.setSn(fLockMAC);
                        pwd.setIdentification(identification);
                        pwd.setGenerateType(SmartLockPwd.PASSWORD_GENERATE_TYPE_CUSTOM);
                        pwd.setPassword(fOpenPassword);
                        pwd.setStartTime(vo.getFBeginDate());
                        pwd.setEndTime(vo.getFEndDate());
                        smartLockPwdService.insertSmartLockPwd(pwd);
                    }

                    // 蓝牙
                    String fBLEPassword = JSONObject.parseObject(object.toString()).getString("fBLEPassword");
                    if (StrUtil.isNotEmpty(fBLEPassword)) {
                        SmartLockBluetooth blue = new SmartLockBluetooth();
                        blue.setSn(fLockMAC);
                        blue.setBluetoothPwd(fBLEPassword);
                        blue.setStartTime(vo.getFBeginDate());
                        blue.setEndTime(vo.getFEndDate());
                        blue.setIdentification(identification);
                        smartLockBluetoothService.insertSmartLockBluetooth(blue);
                    }

                    //指纹
                    if (StrUtil.isNotEmpty(vo.getFFingerFeature()) &&
                            LockYltAccredit.AUTH_STATE_TRUE.equals(vo.getFOpenByFinger())) {
                        SmartLockFingerprint fingerprint = new SmartLockFingerprint();
                        fingerprint.setSn(fLockMAC);
                        fingerprint.setFingerprint(vo.getFFingerFeature());
                        fingerprint.setStartTime(vo.getFBeginDate());
                        fingerprint.setEndTime(vo.getFEndDate());
                        fingerprint.setIdentification(identification);
                        smartLockFingerprintService.insertSmartLockFingerprint(fingerprint);
                    }
                }
                lockYltAccreditService.insertLockYltAccredit(yltAccredit);
            }
        }
    }

}
